package com.boot.unity.api.modules.cert.service.impl;

import com.boot.unity.api.common.Result;
import com.boot.unity.api.constants.Constants;
import com.boot.unity.api.modules.cert.dao.CertDao;
import com.boot.unity.api.modules.cert.entity.Cert;
import com.boot.unity.api.modules.cert.service.CertService;
import com.boot.unity.api.utils.IdUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class CertServiceImpl implements CertService {
    private final CertDao certDao;
    private final RedisTemplate<String,Cert> redisTemplate;

    @Transactional
    @Override
    public Result save(String user) {
        Cert cert = certDao.getByUser(user);
        if (cert != null){
            return new Result("500","用户重复");
        }
        Cert c = new Cert();
        c.setAppId(IdUtil.uuidUpperCase());
        c.setAppSecret(IdUtil.uuidUpperCase());
        c.setUser(user);
        int num = certDao.save(c);
        if (num > 0){
            redisTemplate.boundValueOps(Constants.APPID_KEY +c.getAppId()).set(c);
            return Result.success();
        }
        return Result.fail();
    }

    @Override
    public Result list() {
        Result result = Result.success();
        List<Cert> certList = certDao.list();
        result.setData(certList);
        return result;
    }
}
